package com.github.shiqiyue.myadmin.config.thymeleaf.dialect.processor;

import com.github.shiqiyue.myadmin.config.security.common.AuthorityCommon;
import com.github.shiqiyue.myadmin.util.security.SecurityUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.Arrays;
import java.util.List;

public class AuthorityListProcessor extends AbstractAttributeTagProcessor {
	
	private static final Integer PRECEDENCE = 450;
	
	private static final List<String> PRINT_AUTHS = Arrays.asList(AuthorityCommon.ADD, AuthorityCommon.DELETE,
			AuthorityCommon.EDIT, AuthorityCommon.LIST, AuthorityCommon.EXPORT_EXCEL);
	
	private static final String ATTRIBUTE_PREFIX = "data-auth-";
	
	public AuthorityListProcessor(final TemplateMode templateMode, final String dialectPrefix, final String attrName) {
		super(templateMode, dialectPrefix, null, false, attrName, true, PRECEDENCE, true);
	}
	
	@Override
	protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName,
			String attributeValue, IElementTagStructureHandler structureHandler) {
		for (String printAuth : PRINT_AUTHS) {
			printAuth = printAuth.toLowerCase();
			structureHandler.setAttribute(ATTRIBUTE_PREFIX + printAuth, SecurityUtils.auth(printAuth) + "");
		}
	}
	
}
